package com.example.mgsnew.listeners;

import com.aliyun.oss.ServiceException;
import com.example.common.constants.MqConstants;
import com.example.common.utils.AliOssUtil;
import com.example.mgsnew.Mgs.FileMergeTask;
import com.example.mgsnew.Service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

@Component
@RequiredArgsConstructor
@Slf4j
public class uploadListener {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private FileService fileService;

    // 消息队列处理文件合并与上传
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.QUEUE_FILE_MERGE),
            exchange = @Exchange(name = MqConstants.EXCHANGE_FILE, type = ExchangeTypes.TOPIC),
            key = MqConstants.ROUTING_KEY_FILE_MERGE
    ))
    public void mergeAndUpload(FileMergeTask task) {
        try {
            // 合并分片
            byte[] mergedFile = fileService.mergeChunks(task.getTaskId(), task.getTotalChunks());
            // 构建OSS路径并上传
            String fileType = fileService.getFileExtension(task.getFileName());
            String filePath = task.getType()+"/" +fileType+"/"+ task.getTaskId() + "." + fileType;
            String url = aliOssUtil.saveFile(filePath, new ByteArrayInputStream(mergedFile));
            //删除临时操场的分片文件
            fileService.deleteChunk(task.getTaskId());
            fileService.deleteTaskFromRedis(task.getTaskId());  //删除redis数据
            log.info("大型文件上传完成，URL: {}", url);
        } catch (Exception e) {
            log.error("文件合并上传异常，taskId={}", task.getTaskId(), e);
            throw new ServiceException("大型文件上传失败");
        }
    }
}
